package com.partners.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.partners.constant.ErrorMessageEnum;
import com.partners.constant.PermissionEnum;
import com.partners.dao.dto.UserRoleOutputDTO;
import com.partners.dao.basic.GroupDao;
import com.partners.dao.basic.UserGroupDao;
import com.partners.dao.bo.GroupDO;
import com.partners.dao.bo.UserGroupDO;
import com.partners.model.BusinessException;
import com.partners.model.Paging;
import com.partners.service.GroupService;
import com.partners.service.UserService;
import com.partners.utils.TimestampUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liangyongle
 * @date 2018-12-29
 */
@Service
@Slf4j
public class GroupServiceImpl implements GroupService {

    @Resource
    private GroupDao groupDao;

    @Resource
    private UserService userService;

    @Resource
    private UserGroupDao userGroupDao;

    /**
     * 获取用户分组
     * @param paging Paging
     * return
     * */
    @Override
    public Map<String, Object> getGroupList(Paging paging,Integer id) {
        //查询该用户是否拥有管理员的权限(先用查表，后期再改为用缓存)
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        List<Map<String,Object>> list = groupDao.getGroupListById(id);
        PageInfo pageInfo = new PageInfo(list);
        Object total = pageInfo.getTotal();
        allList.put("total",total);
        allList.put("list",list);
        return allList;
    }




    /**
     * 获取分组下面的用户
     * @param
     * */
    @Override
    public Map<String,Object> getUserByGroupId(Paging paging,Integer id) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        allList.put("total",0);
        allList.put("list","");
        if(id == 0){
            allList.put("title","默认分组");
            //查询所有没有分组的人员
            List<UserRoleOutputDTO> userList = groupDao.getOrtherUserByGroup();
            PageInfo pageInfo = new PageInfo(userList);
            Object total = pageInfo.getTotal();
            allList.put("total",total);
            allList.put("list",userList);
        }else{
            //查询当前分组的人
            GroupDO groupDO = groupDao.selectByPrimaryKey(id);
            if(groupDO == null){
                throw  BusinessException.of(ErrorMessageEnum.GROUPID_NOT_FOUND);
            }
            allList.put("title",groupDO.getName());
            //首先查询所有的user_id
            List<Map<String,Integer>> idList = groupDao.getGroupUserId(id);
            if(idList.size() > 0){
            List<Integer> ids = idList.stream().map(item -> item.get("user_id")).collect(Collectors.toList());
                if(ids != null){
                    List<UserRoleOutputDTO> userList = groupDao.getUserByGroupId(ids);
                    PageInfo pageInfo = new PageInfo(userList);
                    Object total = pageInfo.getTotal();
                    allList.put("total",total);
                    allList.put("list",userList);
                }
            }
        }


     return allList;

    }

    /**
     * 编辑分组
     * @param
     * */
    @Override
    @Transactional
    public Integer editGroup(GroupDO groupDO) {
        //查重
        Integer result = 0;
        Integer exist = groupDao.checkNameGroup(groupDO.getName(),groupDO.getId());
        if(exist !=null){
          throw  BusinessException.of(ErrorMessageEnum.NAME_IS_EXIST);
        }
        if(groupDO.getId() != null){
            //编辑
            groupDao.updateByPrimaryKeySelective(groupDO);
            result = groupDO.getId();
        }else{
            //新增
            groupDO.setAddtime(TimestampUtils.timestamp());
            groupDao.insertSelective(groupDO);
            result = groupDO.getId();
        }
        return result;
    }


    /**
     * 获取分组明细
     * @param
     * */
    @Override
    public GroupDO getGroupeDetail(Integer id) {
        GroupDO groupDO = groupDao.selectByPrimaryKey(id);
        if(groupDO == null){
            throw BusinessException.of(ErrorMessageEnum.RECORD_NOT_FOUND);
        }
        return groupDO;
    }

    /**
     * 用户加入分组
     * @param
     * */
    @Override
    @Transactional
    public void joinGroupUser(Integer groupId, Integer userId) {
        //1.查询该记录是否已经存在
        //2.查询当前用户是否已经加入了其它分组
        Integer exist = groupDao.getGroupExist(groupId,userId);
        if(exist != null){
            throw  BusinessException.of(ErrorMessageEnum.RECORD_IS_EXIST);
        }
        Integer group = groupDao.checkUserJoinGroup(userId);
        if(group != null){
            throw BusinessException.of(ErrorMessageEnum.RECORD_IS_EXIST);
        }

        UserGroupDO userGroupDO = new UserGroupDO();
        userGroupDO.setGroupId(groupId);
        userGroupDO.setUserId(userId);
        userGroupDO.setAddtime(TimestampUtils.timestamp());
        userGroupDao.insertSelective(userGroupDO);
    }


    /**
     * 用户退出分组
     * @Param
     *
     * */
    @Override
    public void leaveGroupUser(Integer id) {
        //查询该记录是否存在
        UserGroupDO userGroup = userGroupDao.selectByPrimaryKey(id);
        if(userGroup == null){
            throw BusinessException.of(ErrorMessageEnum.RECORD_NOT_FOUND);
        }
        userGroupDao.deleteByPrimaryKey(id);
    }


    /**
     * 获取所有分组和其它用户
     * @param uid  Integer
     * @return list
     * */
    @Override
    public Map<String, Object> getGroupUserList(Integer uid,Integer id) {
        Integer code = PermissionEnum.GROUP_LIST.getCode();
        userService.isPermission(uid,code);
        Map<String,Object> allList = new HashMap<>();
        List<Map<String,Object>> list = groupDao.getGroupListById(id);
        Integer order_num = groupDao.getOrderUserTotal();
        for (Map<String,Object> map : list){
            Integer num = groupDao.getGroupTotal((Integer) map.get("id"));
            map.put("total",num);
        }
        Map<String,Object> orther = new HashMap<>();
        orther.put("id","0");
        orther.put("name","默认分组");
        orther.put("pid",0);
        orther.put("total",order_num);
        list.add(orther);
        allList.put("list",list);
        return allList;
    }


    /**
     * 删除分组
     * @param
     * */
    @Override
    @Transactional
    public void deleteGroup(Integer id) {
        //1.查询分组是否存在
        GroupDO groupDO = groupDao.selectByPrimaryKey(id);
        if(groupDO == null){
            throw BusinessException.of(ErrorMessageEnum.RECORD_IS_EXIST);
        }
        if(id ==1 || id == 2){
            throw BusinessException.of(ErrorMessageEnum.OPERATION_FAILURE);
        }
        groupDao.deleteByPrimaryKey(id);
        userGroupDao.deleteByGroupId(id);

    }


}
